package cn.easyutil.project.web.session;


import cn.easyutil.project.base.service.CacheService;
import cn.easyutil.util.javaUtil.StringUtil;

import java.util.Map;

public class RedisSessionCache implements SessionCacheFactory {

    private CacheService cacheService;

    public RedisSessionCache(CacheService cacheService){
        this.cacheService = cacheService;
    }

    @Override
    public String getAesKey(String token) {
        return getUserInfo(token,aesKeyName);
    }

    @Override
    public String getUserId(String token) {
        String userId = getUserInfo(token,"userId");
        return userId;
    }

    @Override
    public void setToken(String token, Long userId) {
        setUserInfo(token,userIdName,userId==null?"":userId.toString());
    }

    @Override
    public void setAesKey(String token, String aesKey) {
        setUserInfo(token, aesKeyName, aesKey);
    }

    @Override
    public void setUserInfo(String token, String key, String val) {
        if(StringUtil.isEmpty(token)){
            return;
        }
        cacheService.setMap(getKey(token), key, val);
        //token过期时间, 默认2小时
        cacheService.set(getKey(token),2*60*60*1000);
    }

    @Override
    public String getUserInfo(String token, String key) {
        if(StringUtil.isEmpty(token)){
            return null;
        }
        return cacheService.getMap(getKey(token),key);
    }

    /**
     * 秒
     * @param phoneNo
     * @param code
     */
    @Override
    public void setSmsCode(String phoneNo, String code,long...expire) {
        long exTime = 3600*1000;
        if(expire.length>0 && expire[0]>0){
            exTime = expire[0];
        }
        cacheService.set(cacheSmsPhone+phoneNo,code,exTime);
    }


    @Override
    public String getSmsCode(String phoneNo) {
        return cacheService.get(cacheSmsPhone+phoneNo);
    }

    @Override
    public void removeSmsCode(String phoneNo) {
        cacheService.delete(cacheSmsPhone+phoneNo);
    }

    @Override
    public void removeToken(String token) {
        cacheService.delete(getKey(token));
    }

    @Override
    public void reletExpire(String token, long expire) {
        if(StringUtil.isEmpty(token)){
            return;
        }
        cacheService.set(getKey(token),expire*1000);
    }
}
